package com.mkx.service;

import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 租户安全服务，用于动态租户权限检查
 */
@Service("tenantSecurityService")
public class TenantSecurityService {

    /**
     * 检查当前用户是否为指定租户的管理员
     * @param authentication 当前认证对象
     * @param tenantId 租户ID
     * @return 是否为租户管理员
     */
    public boolean isTenantAdmin(Authentication authentication, String tenantId) {
        // 从请求头中获取租户ID
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
        String currentTenantId = request.getHeader("X-Tenant-Id");
        
        // 检查用户角色和租户ID
        if (authentication != null && currentTenantId != null) {
            // 检查用户是否为TENANT_ADMIN角色，并且租户ID匹配
            return authentication.getAuthorities().stream()
                    .anyMatch(authority -> "ROLE_TENANT_ADMIN".equals(authority.getAuthority())) &&
                   tenantId.equals(currentTenantId);
        }
        
        return false;
    }
}